package org.mcache;

import java.util.Arrays;
import java.util.Objects;

/**
 * @Author: tjc
 * @description
 * @Date Created in 14:50 2022-08-07
 */
public class ClientResponse {
    public static final String HEADER_SIMPLE_STR = "+";
    public static final String HEADER_ERROR = "-";
    public static final String HEADER_INTEGER = ":";
    public static final String HEADER_BULK_STR = "$";
    public static final String HEADER_ARRAY = "*";
    public static final String CRLF = "\r\n";

    private String content;

    public ClientResponse(String content) {
        this.content = content;
    }

    public static ClientResponse simpleString(String str) {
        return new ClientResponse(HEADER_SIMPLE_STR + str + CRLF);
    }

    public static ClientResponse error(String str) {
        return new ClientResponse(HEADER_ERROR + str + CRLF);
    }


    public static ClientResponse ok() {
        return simpleString("OK");
    }

    public static ClientResponse integer(int value) {
        return new ClientResponse(HEADER_INTEGER + value + CRLF);
    }

    public static ClientResponse bulkString(String... values) {
        int byteLen = Arrays.stream(values).mapToInt(value -> value.getBytes().length).sum();
        StringBuffer buf = new StringBuffer();
        if (values.length == 0) {
            buf.append(CRLF);
        } else {
            Arrays.stream(values).forEach(value -> buf.append(value + CRLF));
        }
        return new ClientResponse(HEADER_BULK_STR + byteLen + CRLF + buf);
    }

    public static ClientResponse array(ClientResponse... responses) {
        StringBuffer content = new StringBuffer(HEADER_ARRAY + responses.length + CRLF);
        for (ClientResponse response : responses) {
            content.append(response.asString());
        }
        return new ClientResponse(content.toString());
    }

    public static ClientResponse nil() {
        return new ClientResponse(HEADER_BULK_STR + -1 + CRLF);
    }

    public String asString() {
        return content;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        ClientResponse response = (ClientResponse) o;
        return Objects.equals(content, response.content);
    }

    @Override
    public int hashCode() {
        return Objects.hash(content);
    }
}
